package com.android.infantschool.ui.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.infantschool.R;
import com.android.infantschool.bean.BaseBean;
import com.android.infantschool.bean.TemperatureRecodeBean;
import com.android.infantschool.model.config.AppConfig;
import com.android.infantschool.model.mvp.presenter.TemperatureRcordPresenter;
import com.android.infantschool.model.mvp.presenter.TemperatureRcordPresenterImpl;
import com.android.infantschool.model.mvp.view.TemperatureRcordView;
import com.android.infantschool.ui.adapter.TemperatureRecodeAdapter;
import com.android.infantschool.ui.view.XYMarkerView;
import com.android.infantschool.ui.view.calendar.bean.DateEntity;
import com.android.infantschool.ui.view.calendar.view.DataView;
import com.android.infantschool.util.DateUtil;
import com.android.infantschool.util.ToastUtil;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.utils.ViewPortHandler;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author Administrator
 * @particulars
 * @time 2019\6\20 0020 15:32
 * @class describe
 */
public class TemperatureCodeActivity extends BaseActivity implements TemperatureRcordView {

    @BindView(R.id.img_back)
    public ImageView imgBack;
    @BindView(R.id.tv_title)
    public TextView tvTitle;
    @BindView(R.id.title)
    public RelativeLayout rlTitle;
    @BindView(R.id.week)
    public DataView week;
    @BindView(R.id.recyclerView)
    public RecyclerView recyclerView;
    @BindView(R.id.tv_baby_title)
    public TextView tvBabyTitle;
    @BindView(R.id.lineChart)
    public LineChart lineChart;

    private TemperatureRecodeAdapter adapter;
    private String babyName = "";

    public static Intent newIntent(Activity activity, String babyName, String babyId) {
        Intent intent = new Intent(activity, TemperatureCodeActivity.class);
        intent.putExtra("babyName", babyName);
        intent.putExtra("babyId", babyId);
        return intent;
    }

    private TemperatureRcordPresenter presenter = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_temperature_record);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        presenter = new TemperatureRcordPresenterImpl(this);
        rlTitle.setPadding(0, this.height, 0, 0);
        tvTitle.setText("测温记录");
        tvBabyTitle.setText(getIntent().getStringExtra("babyName") + "宝宝整天体温情况");

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new TemperatureRecodeAdapter(this);
        recyclerView.setAdapter(adapter);

        this.showLoading();
        week.setOnSelectListener(new DataView.OnSelectListener() {
            @Override
            public void onSelected(DateEntity date) {
                adapter.clear();
                TemperatureCodeActivity.this.showLoading();
                Map<String, String> map = new HashMap<>();
                map.put("token", AppConfig.getToken());
                map.put("babyId", getIntent().getStringExtra("babyId"));
                map.put("time", date.date);
                Log.e(TAG, "week - map:" + map.toString());
                presenter.postTemperatureRcord(map);
            }
        });
        week.getData(DateUtil.getDate(DateUtil.ymd));

        // TODO: 2019/8/2 折线图*********************************start
        Description description = new Description();
        description.setText(DateUtil.getDate(DateUtil.ymd));
        lineChart.setDescription(description);//设置显示在图表右下角的描述文本.也可设置文字大小，颜色，位置，字体
        lineChart.setNoDataText("暂无宝宝当天数据");//设置在图表为空时应显示的文本

        lineChart.getAxisLeft().setAxisMaximum(42);//设置左边Y轴最大值
        lineChart.getAxisLeft().setAxisMinimum(35);//设置左边Y轴最小值
        lineChart.getAxisLeft().setSpaceTop(3);//设置左边Y轴最大值顶部间距
        lineChart.getAxisLeft().setSpaceBottom(5);//设置左边Y轴最小值底部间距
        lineChart.getAxisRight().setEnabled(false);//设置右边Y轴不可见
        lineChart.getAxisLeft().setGranularity(0.5f);
        //x放大5倍  1f代表不放大
        lineChart.zoomToCenter(2.0f, 1f);
        lineChart.setScaleYEnabled(false);
        lineChart.setScaleXEnabled(false);
        setXAxis();
        lineChart.setDragEnabled(true);

        // TODO: 2019/8/2 折线图*********************************end
    }

    /**
     * 添加折线图数据
     *
     * @param list
     */
    private void setData(List<TemperatureRecodeBean.DataBean> list) {

        List<Entry> entityList = new ArrayList<>();

        for (int index = 0; index < list.size(); index++) {
            String data = list.get(index).getExaminationTime();
            float h = Float.parseFloat(data.substring(0, data.indexOf(":")));//时
            float m = Float.parseFloat(data.substring(data.indexOf(":") + 1, data.length()));//分
            float z = h + Float.valueOf(m) / 60f;//比如16:30 等价于 16.5小时
            entityList.add(new Entry(z, Float.valueOf(list.get(index).getResult())));
        }

        // 2.分别通过每一组Entry对象集合的数据创建折线数据集
        LineDataSet lineDataSet = new LineDataSet(entityList, "宝宝当天体温变化");
        lineDataSet.setDrawCircleHole(false);           // 不绘制圆洞，即为实心圆点
        lineDataSet.setColor(0xFF00A29A);            // 设置为红色
        lineDataSet.setMode(LineDataSet.Mode.LINEAR);   // 设置为直线
        lineDataSet.setCubicIntensity(0.15f);           // 强度
        lineDataSet.setCircleColor(0xFF00A29A);      // 设置圆点为颜色
        lineDataSet.setCircleRadius(5f);
        lineDataSet.setLineWidth(1f);                   // 设置线宽为2

        LineData lineData = new LineData(lineDataSet);
        lineData.setDrawValues(false);
        lineChart.setData(lineData);
        lineChart.invalidate();
    }

    private void setXAxis() {
        // X轴
        XAxis xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);  // 在底部
        xAxis.setDrawGridLines(false);                  // 不绘制网格线
        xAxis.setDrawAxisLine(false);
        xAxis.setLabelCount(14);                        // 设置标签数量
        xAxis.setTextColor(0xFF00A29A);                // 文本颜色为灰色
        xAxis.setTextSize(12f);                         // 文本大小为12dp
        xAxis.setGranularity(1.0f);                     // 设置间隔尺寸
        xAxis.setAxisMinimum(6f);                       // 设置X轴最小值
        xAxis.setAxisMaximum(20f);                      // 设置X轴最大值
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);  //设置x轴的位置
        xAxis.setLabelRotationAngle(0f);                //设置文字与x轴之间的角度

        IAxisValueFormatter xAxisFormatter = new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return String.valueOf((int) value).concat(":00");
            }
        };
        xAxis.setValueFormatter(xAxisFormatter);
        XYMarkerView mv = new XYMarkerView(this, xAxisFormatter);//设置悬浮
        mv.setChartView(lineChart);
        lineChart.setMarker(mv);
    }

    @OnClick({R.id.img_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                this.finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.onDestroy();
            presenter = null;
        }
    }

    @Override
    public void errorTemperatureRcord(String error) {
        this.dismissLoading();
        ToastUtil.showShortToast(this, "网络异常:" + error);

    }

    @Override
    public void successTemperatureRcord(BaseBean baseBean) {
        this.dismissLoading();
        TemperatureRecodeBean recodeBean = (TemperatureRecodeBean) baseBean;
        if (recodeBean.getCode() == 0) {
            adapter.setData(recodeBean.getData());
            setData(recodeBean.getData());
        } else {
            lineChart.clear();
            lineChart.invalidate();
            ToastUtil.showShortToast(this, "获取失败:" + recodeBean.getMsg());
        }
    }
}